#include "tcpserver.h"
#include "json_process.h"

#pragma comment(lib, "ws2_32.lib")

int tcpserver_task(int port)
{
    WSADATA wsaData;
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
        std::cerr << "WSAStartup failed: " << WSAGetLastError() << std::endl;
        return 1;
    }

    // 创建TCP服务器套接字
    SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (serverSocket == INVALID_SOCKET) {
        std::cerr << "Socket creation failed: " << WSAGetLastError() << std::endl;
        WSACleanup();
        return 1;
    }

    // 设置套接字选项
    sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = INADDR_ANY;
    serverAddr.sin_port = htons(port);

    // 将套接字绑定到指定端口
    if (bind(serverSocket, (sockaddr*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
        std::cerr << "Bind failed: " << WSAGetLastError() << std::endl;
        closesocket(serverSocket);
        WSACleanup();
        return 1;
    }

    // 监听传入连接
    if (listen(serverSocket, SOMAXCONN) == SOCKET_ERROR) {
        std::cerr << "Listen failed: " << WSAGetLastError() << std::endl;
        closesocket(serverSocket);
        WSACleanup();
        return 1;
    }

    std::cout << "TCP Server is running on port " << port << "..." << std::endl;

    SOCKET clientSocket = INVALID_SOCKET;
    sockaddr_in clientAddr;
    int clientAddrSize = sizeof(clientAddr);

    Json::CharReaderBuilder builder;
    std::unique_ptr<Json::CharReader> jsonReader(builder.newCharReader());
    Json::StreamWriterBuilder writer;

    while (true) {
        fd_set readfds;
        FD_ZERO(&readfds);
        FD_SET(serverSocket, &readfds);
        if (clientSocket != INVALID_SOCKET) {
            FD_SET(clientSocket, &readfds);
        }

        struct timeval timeout;
        timeout.tv_sec = 0;
        timeout.tv_usec = 100000;

        // 等待传入连接或数据
        int activity = select(0, &readfds, NULL, NULL, &timeout);
        if (activity == SOCKET_ERROR) {
            std::cerr << "Select failed: " << WSAGetLastError() << std::endl;
            continue;
        }

        // 接受传入连接
        if (FD_ISSET(serverSocket, &readfds)) {
            SOCKET newSocket = accept(serverSocket, (sockaddr*)&clientAddr, &clientAddrSize);
            if (newSocket == INVALID_SOCKET) {
                std::cerr << "Accept failed: " << WSAGetLastError() << std::endl;
                continue;
            }
            
            // 如果有现有连接，先关闭它
            if (clientSocket != INVALID_SOCKET) {
                std::cout << "Closing existing connection from: " << inet_ntoa(clientAddr.sin_addr) 
                          << ":" << ntohs(clientAddr.sin_port) << std::endl;
                closesocket(clientSocket);
            }
            
            // 接受新连接
            clientSocket = newSocket;
            std::cout << "New client connected from: " << inet_ntoa(clientAddr.sin_addr) 
                      << ":" << ntohs(clientAddr.sin_port) << std::endl;
        }

        // 从客户端接收数据
        if (clientSocket != INVALID_SOCKET && FD_ISSET(clientSocket, &readfds)) {
            char recvBuf[1024];
            int recvResult = recv(clientSocket, recvBuf, sizeof(recvBuf) - 1, 0); // 减少1以确保字符串以null结尾
            if (recvResult > 0) {
                recvBuf[recvResult] = '\0'; // 手动添加null结尾
                std::string errors;
                Json::Value root;

                // 判断是否是完整的JSON字符串
                if (!jsonReader->parse(recvBuf, recvBuf + recvResult, &root, &errors)) {
                    std::cerr << "Failed to parse JSON: " << errors << std::endl;
                    std::string errorMsg = "JSON parse error: " + errors;
                    send(clientSocket, errorMsg.c_str(), errorMsg.size(), 0);
                    continue;
                }

                std::cout << "Received valid JSON: " << root << std::endl;

                // 处理JSON请求
                Json::Value response;
                if (process_json_request(root, response) != 0) {
                    continue;
                }

                // 发送JSON响应
                std::string responseStr = Json::writeString(writer, response);
                // 发送长度+JSON字符串
                uint32_t len = htonl(static_cast<uint32_t>(responseStr.size()));
                std::vector<char> buffer(sizeof(len) + responseStr.size());
                memcpy(buffer.data(), &len, sizeof(len));
                memcpy(buffer.data() + sizeof(len), responseStr.data(), responseStr.size());
                if (send(clientSocket, buffer.data(), buffer.size(), 0) == SOCKET_ERROR) {
                    std::cerr << "Send failed: " << WSAGetLastError() << std::endl;
                    closesocket(clientSocket);
                    clientSocket = INVALID_SOCKET;
                }
            } else if (recvResult == 0) {
                std::cout << "Client disconnected" << std::endl;
                closesocket(clientSocket);
                clientSocket = INVALID_SOCKET;
            } else {
                std::cerr << "Recv failed: " << WSAGetLastError() << std::endl;
                closesocket(clientSocket);
                clientSocket = INVALID_SOCKET;
            }
        }
    }

    // 清理资源
    closesocket(serverSocket);
    WSACleanup();
    return 0;
}
